import React from 'react';
import classnames from 'classnames'
import './style.styl';

class PopupDialog extends React.PureComponent<PopupDialogProps> {
    constructor(props){
        super(props)
        this.childRefs = React.createRef();
    }
    state = {
        visible: false,
        childWidth:null,
        childHeight:null,
    }

    childRefs: any

    close(){
        this.setState({visible:false})
    }

    show(){
        this.setState({visible:true})
        this.props.visibleChange(true);
    }

    componentDidMount(){
        const childDom = this.childRefs;
        this.setState({
            childWidth: childDom.current.clientWidth,
            childHeight: childDom.current.clientHeight
        })
    }

    componentWillReceiveProps(newProps){
        if(!newProps.visible){
            this.setState({visible:newProps.visible})
        }
    }


    render(){
        const { showClose = true, children, content, event = 'click' } = this.props;
        const { visible, childHeight, childWidth } = this.state;
        const cls = classnames({
            main: true,
            showCls: visible
        })

        const sty = {
            top:`${childHeight + 20}px`,
            left:`${childWidth / 2 - 40}px`
        }

        const childrenCount = React.Children.count(children);
        const child = React.Children.only(children);
        if(childrenCount > 1) {
            throw new Error('error! PopupDialog component only accept one child!');
        }
        let newProps = {
            ...child.props,
            ref: this.childRefs
        }

        if(event === 'click'){
            newProps.onClick = () => {
                this.show();
            }
        }else{
            newProps.onMouseOver = () => {
                this.show();
            }
            newProps.onMouseLeave = () => {
                this.close();
            }
        }

        return(
            <React.Fragment>
                <div className='mask' onClick={this.close.bind(this)} style={{display:visible ? 'block' : 'none'}}></div>
                <div className="popup-dialog arrow down">
                    <div className={cls} style={sty}>
                        <span className='arrow up'></span>
                        {
                            showClose ? <span onClick={this.close.bind(this)} className='icon-close'></span> : ''
                        }
                        { content }
                    </div>
                    { React.cloneElement(child, newProps) }
                </div>
            </React.Fragment>
        )
    }
}

export default PopupDialog;
